﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystem;
using ThridGroup.ERP.DTO.ProductionSystemDto.IncomingInspectionDto;
using ThridGroup.ERP.ProductionSystem;

namespace ThridGroup.ERP.Web.Controllers.ProductionSystem
{
    /// <summary>
    /// 来料检验控制器
    /// </summary>
    // [Route("ProductionSystem/IncomingInspection")]
    [Route("IncomingInspection")]
    public class IncomingInspectionController : Controller
    {
        private readonly IncomingInspectionServices _incomingInspectionServices;

        public IncomingInspectionController(IncomingInspectionServices incomingInspectionServices)
        {
            _incomingInspectionServices = incomingInspectionServices;
        } 

        /// <summary>
        /// 视图
        /// </summary>
        /// <returns></returns>
        [HttpGet("IncomingInspectionView")]
        public IActionResult IncomingInspectionView()
        {
            return View();
        }

        /// <summary>
        /// 添加来料检验
        /// </summary>
        [HttpPost("AddIncomingInspection")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddIncomingInspection(CreateIncomingInspectionDto input)
        {

            try
            {
                var id = await _incomingInspectionServices.AddIncomingInspection(input);
                return Json(new { code = 0, msg = "添加成功", id });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 分页及多条件查询来料检验列表
        /// </summary>
        [HttpGet("GetIncomingInspectionList")]
        public async Task<IActionResult> GetIncomingInspectionList(int page, int limit, string incomingInspectionCode = null, string batch = null, string testingResult = null, string testingPerson = null, string productName = null, DateTime? incomingDate = null, DateTime? testingDate = null)
        {
            var result = await _incomingInspectionServices.GetIncomingInspectionList(page, limit, incomingInspectionCode, batch, testingResult, testingPerson, productName, incomingDate, testingDate);
            return Json(new { code = 0, msg = "查询成功", data = result.Items, count = result.TotalCount });
        }

        /// <summary>
        /// 批量删除来料检验
        /// </summary>
        [HttpPost("BatchDelete")]
        public async Task<IActionResult> BatchDelete(int[] ids)
        {
            await _incomingInspectionServices.BatchDeleteAsync(ids.ToList());
            return Json(new { code = 0, msg = "批量删除成功" });
        }

        /// <summary>
        /// 根据ID获取来料检验详情（反填）
        /// </summary>
        [HttpGet("GetById")]
        public async Task<IActionResult> GetById(int id)
        {
            var result = await _incomingInspectionServices.GetByIdAsync(id);
            return Json(new { code = 0, msg = "查询成功", data = result });
        }

        /// <summary>
        /// 删除单条来料检验
        /// </summary>
        [HttpPost("Delete")]
        public async Task<IActionResult> Delete(int id)
        {
            await _incomingInspectionServices.DeleteAsync(id);
            return Json(new { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 修改单条来料检验
        /// </summary>
        [HttpPost("Update")]
        public async Task<IActionResult> Update(CreateIncomingInspectionDto dto)
        {
            await _incomingInspectionServices.UpdateAsync(dto);
            return Json(new { code = 0, msg = "修改成功" });
        }

        /// <summary>
        /// 导出来料检验数据（Excel）
        /// </summary>
        [HttpGet("ExportExcel")]
        public async Task<IActionResult> ExportExcel(string incomingInspectionCode = null, string batch = null, string testingResult = null, string testingPerson = null, string productName = null, DateTime? incomingDate = null, DateTime? testingDate = null)
        {
            var bytes = await _incomingInspectionServices.ExportAsync(incomingInspectionCode, batch, testingResult, testingPerson, productName, incomingDate, testingDate);
            return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "来料检验数据.xlsx");
        }

        /// <summary>
        /// 自动生成检验单编号
        /// </summary>
        [HttpGet("GenerateInspectionCode")]
        public IActionResult GenerateInspectionCode()
        {
            try
            {
                // 生成格式：JY + 年月日 + 4位随机数
                var today = DateTime.Now;
                string inspectionCode = "JY" + today.ToString("yyyyMMdd") + new Random().Next(1000, 9999).ToString();

                return Json(new { code = 0, inspectionCode = inspectionCode });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "生成检验单编号失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 检查检验单编号是否已存在
        /// </summary>
        [HttpGet("CheckInspectionCodeExists")]
        public async Task<IActionResult> CheckInspectionCodeExists(string inspectionCode)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(inspectionCode))
                {
                    return Json(new { code = 1, msg = "检验单编号不能为空" });
                }
                var result = await _incomingInspectionServices.GetIncomingInspectionList(1, 1, inspectionCode, null, null, null, null, null, null);
                bool exists = result.TotalCount > 0;
                return Json(new { code = 0, exists = exists });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查检验单编号失败：" + ex.Message });
            }
        }
    }
}
